
/**
\file
Definition of the nmn::logger class.
\author Sean Tromans
*/

#include <needs_more_ninja/template/output_message.hpp>
#include <boost/thread.hpp>
#include <boost/config.hpp>
#include <fstream>

#if	defined(BOOST_MSVC)
#pragma warning(push)
#pragma warning(disable:4127)
#pragma warning(disable:4100)
#endif

#include <boost/date_time.hpp>

#if	defined(BOOST_MSVC)
#pragma warning(pop)
#endif

namespace nmn
{

	/**
	Constructor.
	@param filename The destination log file.
	\author Sean Tromans
	*/
	inline logger::logger( std::string const & filename )
		:		m_filename( filename )
	{
		std::ofstream file( m_filename.c_str( ), std::ios::out );
		if ( !file.is_open( ) )
		{
			throw cannot_open_file( filename );
		}

		file.close( );

		operator( )( "needs_more_ninja :: log opened." );
	}

	/**
	Deconstructor.
	\author Sean Tromans
	*/
	inline logger::~logger( )
	{
		operator( )( "needs_more_ninja :: log closed." );
	}

	/**
	Outputs a string to the log file.
	@param message The message to output to the log.
	\author Sean Tromans
	*/
	template< typename char_t >
	void logger::operator( )( char_t const * const message )
	{
		operator( )( std::basic_string< char_t >( message ) );
	}

	/**
	Outputs a string to the log file.
	@param message The message to output to the log.
	\author Sean Tromans
	*/
	template< typename char_t, typename traits_t, typename allocator_t >
	void logger::operator( )( std::basic_string< char_t, traits_t, allocator_t > const & message )
	{
		boost::mutex::scoped_lock lock( m_mutex );

		nmn::output_message( message );

		std::ofstream file( m_filename.c_str( ), std::ios::out | std::ios::app );
		if ( file.is_open( ) )
		{
			std::string const output = nmn::create_string( "[%1% | %2%]: %3%\n", boost::posix_time::second_clock::local_time( ), boost::this_thread::get_id( ), message );
			file << output;
		}
	}

}
